package com.lili.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lili.mapper.SubjectMapper;
import com.lili.pojo.Subject;
import com.lili.pojo.Wrong;
import com.lili.service.WrongService;
import com.lili.mapper.WrongMapper;
import com.lili.utils.HTMLUtil;
import com.lili.vo.request.troop.QueryReqVO;
import com.lili.vo.response.troop.WrongDataItem;
import com.lili.vo.response.troop.WrongIndexVO;
import com.lili.vo.response.troop.WrongRespVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class WrongServiceImpl extends ServiceImpl<WrongMapper, Wrong>
        implements WrongService {

    private SubjectMapper subjectMapper;

    @Autowired
    public WrongServiceImpl(SubjectMapper subjectMapper) {
        this.subjectMapper = subjectMapper;
    }

    @Override
    public Wrong selectByQuestionIdAndUserId(Integer questionId, Integer userId) {
        return baseMapper.selectByQuestionIdAndCreateUser(questionId, userId);
    }

    @Override
    public IPage<WrongIndexVO> pageList(QueryReqVO vo) {
        IPage<WrongIndexVO> page = new Page<>(vo.getPageIndex(), vo.getPageSize());
        IPage<WrongIndexVO> pages = baseMapper.selectWrongList(page, vo);
        return pages;
    }

    @Override
    @Transactional(readOnly = true)
    public WrongRespVO selectWrongsByPage(QueryReqVO vo) {
        WrongRespVO mode = new WrongRespVO();
        Subject subject = subjectMapper.selectById(vo.getSubjectId());
        mode.setSubjectName(subject.getSubjectName());
        IPage<WrongDataItem> page = new Page<>(vo.getPageIndex(), vo.getPageSize());
        IPage<WrongDataItem> pages = baseMapper.selectWrong(page, vo);
        if (pages.getPages() < vo.getPageIndex()) {
            page = new Page<>(pages.getPages(), vo.getPageSize());
            pages = baseMapper.selectWrong(page, vo);
        }
        List<WrongDataItem> records = pages.getRecords();
        records.forEach(wrongDataItem -> {
            wrongDataItem.setQuestionName(HTMLUtil.clear(wrongDataItem.getQuestionName()));
            wrongDataItem.setAnswerA(HTMLUtil.clear(wrongDataItem.getAnswerA()));
            wrongDataItem.setAnswerB(HTMLUtil.clear(wrongDataItem.getAnswerB()));
            wrongDataItem.setAnswerC(HTMLUtil.clear(wrongDataItem.getAnswerC()));
            wrongDataItem.setAnswerD(HTMLUtil.clear(wrongDataItem.getAnswerD()));
            wrongDataItem.setQuestionDesc(HTMLUtil.clear(wrongDataItem.getQuestionDesc()));
        });
        pages.setRecords(records);
        mode.setWrongs(pages.getRecords());
        return mode;
    }
}




